<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/16
 * Time: 16:59
 * 绑定用户
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\UserBind;
use think\Db;

class Binduser extends Api{
	protected $noNeedRight = ['*'];
	
	/**
	 * 绑定查看帐号
	 * @throws \think\exception\DbException
	 */
	public function bind(){
		$mobile = input('post.mobile');
		$password = input('post.password');
		$remark = input('post.remark');
		
		if(!$mobile || !$password || !$remark) {
			$this->error('参数错误');
		};
		
		$userId = $this->auth->id;
		
		$user = \app\admin\model\User::get(['mobile' => $mobile]);
		!$user && $this->error('用户不存在');
		
		if($userId == $user['id']) {
			$this->error('你想把自己绑了吗？');
		}
		
		if($password != $user['bind_password']) {
			$this->error('口令不正确');
		}
		
		$model = new UserBind();
		$res = $model->bindUser($userId, $user['id'], $remark);
		if($res) {
			$this->success('绑定成功');
		} else {
			$this->error($model->getError());
		}
	}
	
	
	/**
	 * 查询绑定的用户
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function users(){
		$userId = $this->auth->id;
		
		$type = input('post.type', 1, 'intval');
		
		$where['b.status'] = UserBind::STATUS_Y;
		if($type == 1) {
			//我绑定的
			$where['b.user_id'] = $userId;
			$users = Db::name('userBind')->alias('b')
				->join('user u', 'b.target_user_id = u.id', 'left')
				->where($where)
				->field(['u.mobile, b.id, b.target_user_id, b.remark'])
				->select();
		} else {
			//绑定我的
			$where['b.target_user_id'] = $userId;
			$users = Db::name('userBind')->alias('b')
				->join('user u', 'b.user_id = u.id', 'left')
				->where($where)
				->field(['u.mobile, b.id, b.target_user_id, b.remark'])
				->select();
			
			$users[] = ['target_user_id' => $userId, 'remark' => '我'];
		}
		
		
		
		
		$this->success('查询成功', $users);
	}
	
	/**
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
	public function unbind(){
		$id = input('post.id');
		!$id && $this->error('参数错误');
		
		$res = Db::name('userBind')
			->where(['user_id' => $this->auth->id, 'id' => $id])
			->update(['status' => UserBind::STATUS_N]);
		
		if($res !== false) {
			$this->success('解绑成功');
		} else {
			$this->error('解绑出错');
		}
	}
}